package com.ruoyi.file.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.file.bean.FileUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * FastDFS 文件存储。
 *
 * @author william.zhao & zhao xiang.
 * @version 1.0
 * @since jdk-17.0.2
 * @date 2023/05/05
 */
@Service
public class FastDfsSysFileServiceImpl extends AbstractFileService {
    /** 域名或本机访问地址。 */
    @Value("${fdfs.domain}")
    public String domain;

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * FastDfs文件上传接口。
     *
     * @param file 上传的文件。
     * @return the upload result, result[0] means the url, result[1] means the file path.
     * @throws Exception
     */
    @Override
    public FileUploadResult uploadFile(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        StorePath storePath = storageClient.uploadFile(inputStream, file.getSize(),
                FileTypeUtils.getExtension(file), null);
        inputStream.close();
        String url = domain + "/" + storePath.getFullPath();

        FileUploadResult uploadResult = new FileUploadResult();
        uploadResult.setUrl(url);
        uploadResult.setFilePath(storePath.getFullPath());
        return uploadResult;
    }

    /**
     * remove file by file path in hsf. the program had no way to detect if delete success or not.
     * so just return "success".
     *
     * @param filePath the file path in server.
     * @return success or fail.
     */
    @Override
    public String removeFile(String filePath) {
        storageClient.deleteFile(filePath);
        return "success";
    }


}
